<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            @change="changePlant"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in plants"
              :key="item.id"
              :label="item.organizationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成品物料">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择成品物料"
            :disabled="!searchParam.plantId"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button
                type="success"
                :disabled="!searchParam.plantId"
                plain
                @click="showWorkOrderSelect"
                >选择</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="BOM编号">
          <el-input
            v-model="searchParam.bomCode"
            placeholder="请输入BOM编号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="primary"
          plain
          :disabled="ids.length === 0"
          @click="copyDetails()"
          ><i-ep:document-copy />复制</el-button
        >
        <!-- <el-button
          type="success"
          @click="excelBoxOpen"
          :disabled="ids.length !== 1"
          ><i-ep-upload />导入
        </el-button> -->
        <el-button type="success" @click="excelBoxOpen"
          ><i-ep-upload />导入
        </el-button>
        <el-dialog
          :close-on-click-modal="false"
          title="BOM明细数据导入"
          v-model="excelBox"
          width="555px"
          @close="resetFile"
        >
          <div>
            <el-button
              @click="useDownload('/mes/mesbom/exportTemp', 'BOM明细上传模板')"
            >
              <template #icon>
                <i-ep-download />
              </template>
              BOM明细上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              :key="uploadKey"
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>

        <el-button
          class="ml-3"
          :disabled="ids.length !== 1"
          @click="useDownload('/mes/mesbom/export', 'BOM明细', { ids })"
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        @selection-change="handleSelectionChange"
        row-key="id"
        border
        :maxHeight="tableHeight"
        :tree-props="{ children: 'nodes', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="物料"
          prop="materialCode"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="数量"
          prop="matQuantity"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ scope.row.baseQuantity }}
            {{ useDictionary("MeasurementUnit", scope.row.baseQuantityUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="工厂"
          prop="plantName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="BOM编号"
          prop="bomCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="BOM描述"
          prop="bomDescription"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="340" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="添加物料"
              placement="top"
            >
              <el-button
                type="success"
                size="small"
                link
                @click="openSubDialog(scope.row)"
              >
                <i-ep-plus />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openEditDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesbom-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :parentId="addDialog.parentId"
      @reset-table="search"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <mesbomdetail-edit
      :visible="addSubDialog.visible"
      :title="addSubDialog.title"
      :data="addSubDialog.data"
      :parentId="addSubDialog.parentId"
      :bom="addSubDialog.bom"
      :bomId="addSubDialog.bomId"
      :parentBom="addSubDialog.parentBom"
      @reset-table="getTableList"
      :is-readonly="addSubDialog.readvisible"
      @change-visible="changeSubVisible"
    />
    <mesbomdetail-copy
      :visible="copyDialog.visible"
      :ids="copyDialog.ids"
      @reset-table="getTableList"
      @change-visible="changeCopyVisible"
    />

    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import { useDictionary, useDownload, useTable,useComputeTableHeight } from "@/utils/useTable";
import request from "@/utils/request";
import { Edit, Minus, Plus } from "@element-plus/icons-vue";

defineOptions({
  name: "MESMESBOM",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesbom/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  bomCode: "",
  materialId: "",
  materialCode: "",
  plantId: "",
  treeBomCode: "",
};

const deleteParam = {
  api: "/mes/mesbom/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

const dataTableRef = ref(null);
const selectedRows = ref([]);
const ids = ref([]);


// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const addSubDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  bom: {},
  bomId: "",
  parentBom: {},
  data: {},
});
const copyDialog = reactive<DialogOption>({
  visible: false,
  ids: [],
});

// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `/mes/mesbom/get/${id}`,
    method: "get",
  });
  return data;
}

// 查询详情
async function getSubInfo(id: string) {
  request({
    url: `/mes/mesbomdetail/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addSubDialog.data = data.data;
      addSubDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开生产BOM表单弹窗 */
async function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改生产BOM";
    const info = await getInfo(roleObj.id);
    addDialog.visible = true;
    addDialog.data = info;
  } else {
    addDialog.title = "新增生产BOM";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开生产BOM表单弹窗 */
async function openSubDialog(roleObj?: Object) {
  if (roleObj) {
    addSubDialog.title = "新增生产BOM";
    if (roleObj.parentBomId === "0") {
      addSubDialog.parentBom = {};
      addSubDialog.bom = await getInfo(roleObj.id);
    } else {
      addSubDialog.bom = {};
      addSubDialog.parentBom = await getInfo(roleObj.parentBomId);
    }
    addSubDialog.visible = true;
    addSubDialog.parentId = roleObj.parentBomId;
    addSubDialog.bomId = roleObj.id;
  }
  addSubDialog.readvisible = false;
}

/** 打开生产BOM表单弹窗 */
async function openEditDialog(roleObj?: Object) {
  if (roleObj) {
    if (roleObj.parentBomId === "0") {
      openDialog(roleObj);
    } else {
      addSubDialog.title = "修改生产BOM";
      addSubDialog.bom = {};
      addSubDialog.parentBom = await getInfo(roleObj.parentBomId);
      addSubDialog.data = await getSubInfo(roleObj.id);
      addSubDialog.visible = true;
      addSubDialog.parentId = roleObj.parentBomId;
      addSubDialog.bomId = roleObj.id;
    }
  }
  addSubDialog.readvisible = false;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function changeSubVisible(value: boolean) {
  addSubDialog.visible = value;
  if (!value) {
    addSubDialog.data = {};
  }
}
function changeCopyVisible(value: boolean) {
  copyDialog.visible = value;
  if (!value) {
    copyDialog.ids = [];
  }
}

async function deleteItem(roleObj?: Object) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      if (roleObj.parentBomId === "0") {
        const { data } = await request({
          url: `/mes/mesbom/deleteItem/${roleObj.id}`,
          method: "post",
        });
      } else {
        const { data } = await request({
          url: `/mes/mesbomdetail/deleteItem/${roleObj.id}`,
          method: "post",
        });
      }
    } finally {
      getTableList();
    }
  });
}

const copyDetails = () => {
  copyDialog.visible = true;
  copyDialog.ids = ids.value;
};

onMounted(() => {
  search();
  getPlants();
});

// 导入excel
const uploadApi = "/mes/mesbomdetail/upload";
const uploadApiNew = "/mes/mesbom/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");
const uploadKey = ref(Math.random());

function excelBoxOpen() {
  // if (!ids.value[0]) {
  //   ElMessage.error("请先选择要添加的BOM");
  //   return;
  // }
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

const resetFile = () => {
  excelBox.value = false;
  uploadBtn.value = false;
  fileName.value = "";
  uploadFile.value = "";
  uploadKey.value = Math.random();
};

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  // request
  //   .post(`${uploadApi}/${ids.value[0]}`, formdata, config)
  //   .then(({ data }) => {
  //     ElMessage({
  //       type: "success",
  //       message: "上传成功！",
  //     });
  //     resetFile();
  //     search();
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });
  request
    .post(uploadApiNew, formdata, config)
    .then(({ data }) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });
      resetFile();
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}
const plants = ref([]);
const getPlants = async () => {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
};

const changePlant = (val) => {
  if (!val) return;
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};

const handleSelectionChange = (val) => {
  if (val.length === 0) {
    selectedRows.value = [];
    ids.value = [];
    return;
  }

  const lastSelected = val[val.length - 1];
  const parentKey = getParentKey(lastSelected.id);

  const filteredRows = val.filter((row) => getParentKey(row.id) === parentKey);

  if (filteredRows.length !== val.length) {
    dataTableRef.value.clearSelection();
    filteredRows.forEach((row) => {
      dataTableRef.value.toggleRowSelection(row, true);
    });
  }

  selectedRows.value = filteredRows;
  ids.value = filteredRows.map((row) => row.id);
};
const getParentKey = (id) => {
  const flattenTree = (tree) => {
    return tree.reduce((acc, node) => {
      return acc.concat(node, flattenTree(node.nodes));
    }, []);
  };
  const row = flattenTree(tableData.value).find((item) => item.id === id);

  return row?.parentBomId;
};
</script>

<style scoped>
::v-deep
  .el-table__header-wrapper
  th.el-table-column--selection
  .cell
  .el-checkbox {
  display: none;
}
</style>
